package org.jeecg.modules.car.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.entity.car.CarMerchantDerate;
import org.jeecg.enums.car.CarDerateStatusEnum;
import org.jeecg.enums.car.CarDerateTypeEnum;
import org.jeecg.modules.car.entity.*;
import org.jeecg.modules.car.service.ICarMerchantDerateService;
import org.jeecg.modules.car.service.ICarMerchantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 定时任务接口
 *
 * @author: Shaopeng
 * @date： 日期：2020年10月24日
 */
@Slf4j
@Api(tags = "定时任务接口")
@RestController
@RequestMapping(value = "/car/quartz")
public class CarQuartzController{

    @Autowired
    private ICarMerchantService carMerchantService;

    @Autowired
    private ICarMerchantDerateService carMerchantDerateService;

    @ApiOperation("定时删除已经过期优惠卷")
    @Async("/asyncExecutor")
    @PostMapping(value = "/refreshExpiredDerate")
    public void refreshExpiredDerate(){
        log.info(DateUtils.now()+"开始同步删除过期优惠卷信息");
        long startTime = System.currentTimeMillis();
        try {
            LambdaQueryWrapper<CarMerchantDerate> query = new LambdaQueryWrapper<>();
            //查询优惠卷已经过期  && 未使用/已经发送
            query.lt(CarMerchantDerate::getEndTime, new Date());
            query.eq(CarMerchantDerate::getStatus, CarDerateStatusEnum.CAR_DERATE_STATUS_0.getCode()).or().eq(CarMerchantDerate::getStatus, CarDerateStatusEnum.CAR_DERATE_STATUS_1.getCode());
            List<CarMerchantDerate> merchantDerates = carMerchantDerateService.list(query);
            if (merchantDerates.size() > 0){
                for (int i = 0; i <merchantDerates.size(); i++){
                    //查询到商家信息
                    CarMerchant carMerchant =  carMerchantService.getById(merchantDerates.get(i).getMerchantId());
                    //优惠券信息
                    CarMerchantDerate carMerchantDerate =  merchantDerates.get(i);
                    if (carMerchant != null){
                        carMerchantDerate.setStatus(CarDerateStatusEnum.CAR_DERATE_STATUS_MISS.getCode());
                        carMerchantDerate.setRemarks("定时任务设置优惠卷已失效");
                        //修改优惠卷状态
                        carMerchantDerateService.updateById(carMerchantDerate);
                        //非系统商家发放的优惠券反还余额
                        if (carMerchantDerate.getDerateType().equals(CarDerateTypeEnum.CAR_DERATE_TYPE_0.getCode())){
                            //优惠卷剩余次数
                            Integer remainder = carMerchantDerate.getUsableNumber() - carMerchantDerate.getUsedNumber();
                            //反还商家余额  = 商家余额 +  优惠卷金额
                            carMerchant.setRemainAmount(carMerchant.getRemainAmount().add(carMerchantDerate.getDerateAmount().multiply(BigDecimal.valueOf(remainder))));
                            log.info("定时任务设置优惠卷id：{}， 优惠卷次数：{}， 使用次数：{}， 退还金额：{} ， 商家余额：{}",carMerchantDerate.getId(), carMerchantDerate.getUsableNumber(), carMerchantDerate.getUsedNumber(),carMerchantDerate.getDerateAmount().multiply(BigDecimal.valueOf(remainder)));
                            //反还商家余额  = 商家余额 +  优惠卷金额
                            //carMerchant.setRemainAmount(carMerchant.getRemainAmount().add(carMerchantDerate.getDerateAmount()));
                        }
                    }else {
                        log.error("惠券id：{}同步异常 未查询到商户信息",carMerchantDerate.getId());
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            log.error("定时同步优惠卷信息异常！");
        }finally {
            log.info("同步过期优惠卷信息完成，共耗时"+(System.currentTimeMillis()-startTime));
        }
    }


}
